package com.acme.javaschool.intense.sems.sem2concurrency.computing.cached;

import com.acme.javaschool.intense.sems.sem2concurrency.computing.Computable;

import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

public class FutureCachedComputable <A, V> implements Computable<A, V> {

    private final ConcurrentMap<A, Future<V>> cache = new ConcurrentHashMap<>();
    private final Computable<A, V> computable;

    public FutureCachedComputable (Computable<A, V> computable) {
        this.computable = computable;
    }

    @Override
    public V compute(final A arg) throws InterruptedException {
        Future<V> result = cache.get(arg);
        if (result == null) {
            FutureTask<V> ft = new FutureTask<>(new Callable<V>() {

                @Override
                public V call() throws Exception {
                    return computable.compute(arg);
                }
            });
            result = cache.putIfAbsent(arg, ft);
            if (result == null) {
                ft.run();
                result = ft;
            }
        }
        try {
            return result.get();
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int getCount() {
        return computable.getCount();
    }

    @Override
    public void reset() {
        computable.reset();
    }

}
